// 乘法，解决js计算精度问题
function floatMultiply(arg1: number, arg2: number): any {
  if (arg1 == null || arg2 == null || arg1 === undefined || arg2 === undefined) {
    return null;
  }
  let n1, n2;
  let r1, r2; // 小数位数
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  n1 = Number(arg1.toString().replace('.', ''));
  n2 = Number(arg2.toString().replace('.', ''));
  return (n1 * n2) / Math.pow(10, r1 + r2);
}
// 加法，解决js计算精度问题
function floatAdd(arg1: number, arg2: number): any {
  if (arg1 == null || arg2 == null || arg1 === undefined || arg2 === undefined) {
    return null;
  }
  let r1, r2, m;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (floatMultiply(arg1, m) + floatMultiply(arg2, m)) / m;
}
// 减法，解决js计算精度问题
function floatSub(arg1: number, arg2: number): any {
  if (arg1 == null || arg2 == null || arg1 === undefined || arg2 === undefined) {
    return null;
  }
  let r1, r2, m, n;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = r1 >= r2 ? r1 : r2;
  return ((floatMultiply(arg1, m) + floatMultiply(arg2, m)) / m).toFixed(n);
}
// 除法，解决js计算精度问题
function floatDivide(arg1: number, arg2: number): any {
  if (arg1 == null || arg2 == null || arg2 === 0 || arg1 === undefined || arg2 === undefined) {
    return null;
  }
  let n1, n2;
  let r1, r2; // 小数位数
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  n1 = Number(arg1.toString().replace('.', ''));
  n2 = Number(arg2.toString().replace('.', ''));
  return (n1 / n2) * Math.pow(10, r2 + r1);
}

export default {
  floatMultiply,
  floatAdd,
  floatSub,
  floatDivide,
};
